package com.bdqn.controller;

import com.bdqn.base.R;
import com.bdqn.logger.WebLogger;
import com.bdqn.pojo.Seckill;
import com.bdqn.service.SeckillService;
import com.bdqn.util.DateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * SeckillController
 *
 * @author LILIBO
 * @since 2024/4/19
 */
@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private SeckillService seckillService;

    /**
     * 商品秒杀
     *
     * @param seckillId 秒杀活动ID
     */
    @WebLogger("商品秒杀")
    @PostMapping("/viebuy")
    public R viebuy(@RequestParam("seckillId") Long seckillId) {
        // 找到当前秒杀活动
        Seckill seckill = seckillService.getById(seckillId);

        // 不在活动时间范围
        if (DateUtil.afterNowDate(seckill.getStartTime(), DateUtil.YYYY_MM_DD_HH_MM_SS) || DateUtil.beforeNowDate(seckill.getEndTime(), DateUtil.YYYY_MM_DD_HH_MM_SS)) {
            return R.failure("不在活动时间，请继续关注！");
        }
        // 秒杀商品已被抢光
        if (seckill.getStockCount() <= 0) {
            return R.failure("秒杀失败，商品已被抢光！");
        }

        // 调用秒杀服务
        long orderId = seckillService.viebuy(seckillId);


        return R.success("【秒杀模块 - " + serverPort + "】秒杀成功: ");
    }

}
